package com.grp6.game.chess.player;

import java.util.ArrayList;
import java.util.List;

import com.grp6.game.chess.ChessMove;
import com.grp6.game.chess.model.ChessPiece;
import com.grp6.game.chess.model.ChessPlace;
import com.grp6.game.model.IPiece;
import com.grp6.game.player.IHumanPlayer;

public class ChessHumanPlayer implements IHumanPlayer,IChessPlayer {

	private List<ChessPiece> pieces = new ArrayList<ChessPiece>();
	private boolean hasWon = false;
	private ChessMove nextMove = null;
	private boolean playing;

	@Override
	public synchronized ChessMove getNextMove() {
		while(nextMove==null)
			try {
				this.wait();
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
		try{
			return nextMove;
		}finally{
			nextMove = null;
		}
	}

	@Override
	public boolean isHasWon() {
		return hasWon;
	}

	@Override
	public void setHasWon(boolean hasWon) {
		this.hasWon = hasWon;

	}

	@Override
	public List<ChessPiece> getPieces() {
		return pieces ;
	}
	
	public void setPlaying(boolean playing){
		this.playing = playing;
	}
	
	public boolean isPlaying(){
		return playing;
	}

	@Override
	public void setPieces(List<IPiece> pieces) {
		//FIXME todo
	}
	
	private ChessPiece source;
	public boolean onStartMove(ChessPiece piece){
		
		return false;
	}
	
	public synchronized void onPlaceHit(ChessPlace place) {
		if(source==null && place.getPieces().size()>0 && 
				pieces.contains(place.getPieces().get(0))){
			source = place.getPieces().get(0);
		}else if (source!=null && 
				(place.getPieces().size()==0 || 
						!pieces.contains(place.getPieces().get(0)))){
			nextMove = new ChessMove(source, place);
			source = null;
			this.notify();
			playing = false;
		}
	}

}
